const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpackMerge         = require('webpack-merge')
const webpackCommon        = require('./webpack.common.js')
const CssOptimize          = require('optimize-css-assets-webpack-plugin')
const CssNano              = require('cssnano')
const Terser			   = require('terser-webpack-plugin')
const CleanWebpack		   = require('clean-webpack-plugin')
const webpack              = require('webpack')

module.exports=webpackMerge(webpackCommon,{
	mode:"production",
	output:{
		filename     : "js/[name].[chunkhash:6].js",
		// 内容不变，hash不变，会影响到splitChunk分离出的chunkfiles
		chunkFilename: 'js/[name].[contenthash:6].js'
	},
	optimization: {
	    splitChunks: {
	        chunks: "all"
	    },
	    // 运行时所需chunk提取
	    runtimeChunk:{
	    	name:"runtime"
	    },
	    minimizer:[
		    new CssOptimize({
				// 用cssnano规则压缩css
				cssProcessor:CssNano,
				cssProcessorOptions:{
					// 删除注释
					discardComments:{ removeAll: true}
				},
				canPrint:true
			}),
			// js压缩
			new Terser()
		]
	},
	plugins:[
		// 每次打包前自动清理dist目录
		new CleanWebpack(['dist']),
		// 生产环境下，未变动模块hash的保持
		new webpack.HashedModuleIdsPlugin(),
		// 提取、压缩css和less,[contenthash]保证了内容不更改的情况下hash不变
		new MiniCssExtractPlugin({
			filename:"css/[name].[contenthash:6].css",
		})
	],
	module:{
		rules:[
			{
				test:/\.css$/,
				use:[
					// 当前模式(production)下提取css
					{	loader: MiniCssExtractPlugin.loader,						
						options:{
							// 此路径保证了静态资源的可访问性
							publicPath:"../"							
						}
					},
					{
						loader:"css-loader",
						options:{
							minimize:true
						}
					},						
					"postcss-loader"
				]
			},
			{	
				// 当前模式(production)下提取less
				test:/\.less$/,
				use:[
					// 当前模式(production)下提取css
					{	loader: MiniCssExtractPlugin.loader,						
						options:{
							// 此路径保证了静态资源的可访问性
							publicPath:"../"							
						}
					},
					{
						loader:"css-loader",
						options:{
							minimize:true
						}
					},						
					"postcss-loader",
					"less-loader"
				]
			}
		]
	}
})


